#!/bin/sh

function getPkgInfo() {
        pkgName=$1

        pkgDumpInfo=$(dumpsys package $pkgName |  grep -iE 'versionName|versionCode|userId|timeStamp|firstInstallTime|lastUpdateTime')

        versionName=$(echo "$pkgDumpInfo"      | grep 'versionName'      | awk -F'versionName=' '{print $NF}')
        versionCode=$(echo "$pkgDumpInfo"      | grep 'versionCode'      | xargs)
        userId=$(echo "$pkgDumpInfo"           | grep 'userId'           | awk -F'userId=' '{print $NF}')
        timeStamp=$(echo "$pkgDumpInfo"        | grep 'timeStamp'        | awk -F'timeStamp=' '{print $NF}')
        firstInstallTime=$(echo "$pkgDumpInfo" | grep 'firstInstallTime' | awk -F'firstInstallTime=' '{print $NF}')
        lastUpdateTime=$(echo "$pkgDumpInfo"   | grep 'lastUpdateTime'   | awk -F'lastUpdateTime=' '{print $NF}')

        echo "{\"package_name\":\"$pkgName\",\"versionName\":\"$versionName\",\"versionCode\":\"$versionCode\",\"uid\":$userId,\"timeStamp\":\"$timeStamp\",\"firstInstallTime\":\"$firstInstallTime\",\"lastUpdateTime\":\"$lastUpdateTime\"}"
}


pkgsInfo=''
for pkg in $(pm list package -3 | awk -F':' '{print $NF}')
do
pkgsInfo="$(getPkgInfo $pkg),${pkgsInfo}"

done

# remove last ','
echo "[${pkgsInfo%?}]"
#echo "[${pkgsInfo}]"
